package management;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import utilities.Constants;
import model.Candidato;

public class ApplicationManager{

	private HashMap<String, Candidato> candidatesMap;
	private static Integer currentId;
	
	public ApplicationManager(){
		this.candidatesMap = new HashMap<String, Candidato>();
		ApplicationManager.currentId = 0;
	}
	
	public Boolean addNewCandidate(Candidato c){
		if (!this.candidatesMap.containsKey(c.getName())){
			this.candidatesMap.put(c.getName(), c);
			return true;
		}
		return false;
	}
	
	public List<Candidato> getCandidates(){
		ArrayList<Candidato> c = new ArrayList<Candidato>();
		for (String s : this.candidatesMap.keySet()) {
			c.add(this.candidatesMap.get(s));
		}
		return c;
	}

	public void removeCandidate(String nombreCandidato) {
		if (this.candidatesMap.containsKey(nombreCandidato)){
			this.candidatesMap.remove(nombreCandidato);
		}
	}
	
	public Candidato getCandidate(String nombre){
		return this.candidatesMap.get(nombre);
	}
	
	public void guardar(){
		FileHelper.writeFile(Constants.archivoVotacion, ApplicationManager.currentId, this.candidatesMap);
	}
	
	public void cargar(){
		try {
			String file = FileHelper.readFile(Constants.archivoVotacion, Charset.defaultCharset());
			ConfigurationParser.parse(file);
			ApplicationManager.currentId = ConfigurationParser.getId();
			for (Candidato c : ConfigurationParser.getCandidatos()) {
				this.candidatesMap.put(c.getName(), c);
			}
		} catch (IOException e) {
			FileHelper.writeFile(Constants.archivoVotacion, ApplicationManager.currentId, this.candidatesMap);
		}
	}

	public static Integer getCurrentId() {
		return ++currentId;
	}

	public void restart() {
		for (String s : this.candidatesMap.keySet()) {
			Candidato candidato = this.candidatesMap.get(s);
			candidato.setCantVotos(0);
			this.candidatesMap.put(candidato.getName(), candidato);
		}
	}
	
}
